package code.command {

import code.Model;
import code.event.InsertTopicEvent;
import code.remote.ResultErrorContainer;
import code.view.InsertTopicPopup;
import code.view.PopupClosedEvent;
import code.vo.Category;
import code.vo.NeededTopic;
import code.vo.OfferedTopic;
import code.vo.Topic;

import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;

import logging.Logger;

import mx.controls.Alert;

public class InsertTopicCommand implements ICommand {
	
	private static const LOG: Logger = Logger.getLogger("code.command.InsertTopicCommand");
	
	public function InsertTopicCommand() {
	}
	

	public function execute(_event: CairngormEvent):void {
		const event: InsertTopicEvent = _event as InsertTopicEvent;
		LOG.fine("Executing insert vote [event="+event+"].");
		
		const popup: InsertTopicPopup = new InsertTopicPopup();
		popup.addEventListener(PopupClosedEvent.POPUP_CONFIRMED, onPopupConfirmed);
		popup.doDisplay();
	}
	
	private function onPopupConfirmed(event: PopupClosedEvent): void { 
		LOG.finer("onPopupConfirmed() invoked");
		const err: ResultErrorContainer = event.errorContainer as ResultErrorContainer;
		
		if(err.errorCode == 0) {
			
			// TODO duplicate code
			const insertedTopic: Topic = event.confirmedObject as Topic;
			if(insertedTopic is NeededTopic) {
				const ntopic: NeededTopic = insertedTopic as NeededTopic;
				const ntargetCategory: Category = Model.instance.getNeededCategoryById(ntopic.categoryId);
				ntargetCategory.topics.addItem(ntopic);
				
				Model.instance.neededTopicsAdvancedDataGridHack.invalidateList();
				
			} else if(insertedTopic is OfferedTopic) {
				const otopic: OfferedTopic = insertedTopic as OfferedTopic;
				const otargetCategory: Category = Model.instance.getOfferedCategoryById(otopic.categoryId);
				otargetCategory.topics.addItem(otopic);
				
				Model.instance.offeredTopicsAdvancedDataGridHack.invalidateList();
				
			} else {
				throw new Error("Unhandled topic type: " + insertedTopic);
			}
			
			Alert.show("Successfully inserted topic '" + insertedTopic.title + "'.", "Topic Inserted");
		} else {
			Alert.show(err.errorMessage, "Error Inserting Topic");
		}
	}
	
}
}